<?php
class Subscribe_model extends CI_Model {

	function __construct()
    {
        parent::__construct();
    }
	/**
	 * 新增
	 */
	public function add($data) {   
		
		$this->db->insert("subscribes", $data);
		return $this->db->insert_id();
	}
	
	
 	/**
	 * 获取订阅信息
	 * @param int $id
	 */
	public function find_by_id($id) {
		$this->db->where('id', $id);
		return $this->db->get('subscribes')->row_array();
	}
	public function remove($id) {
		$this->db->where('id', $id);
		$this->db->delete('subscribes'); 
	}
	
	
	public function find_subscribes($user_id, $offset = 0, $limit = 20) {
		$sql = " select p.province,s.*,c.city,a.area, ct.name from subscribes s
		left join province p on s.province=p.provinceID
		left join city c on s.city=c.cityID
		left join area a on s.area = a.areaID
		left join categories ct on s.categroy_id=ct.id
		where s.created_by=" . $user_id . "  order by s.created desc ";
		$sql .= " limit " . $offset . "," . $limit;
		print $sql;
		$result =  $this->db->query($sql)->result_array();
		for ($i = 0, $n = count($result); $i < $n; $i++) {
			$result[$i]['title'] = $result['province'] . $result['city'] .$result['area'] .$result['name']; 
		}
		//print_r($result);
		return $result;
	}

	public function get_count_favourite_story($user_id) {
		$sql = " select count(*) as total from favourites where target_type='story' and user_id=" . $user_id;
		$result = $this->db->query($sql)->row_array();
		return $result['total'];
	}
}